package niit.wei.dao.impl;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author WeiJinLong
 * @Date 2023-06-29 11:02
 * @Version 1.0
 */
public class BaseDaoImpl<T> {
    public void update(Connection connection, String sql ,Object...args) throws SQLException {
        PreparedStatement pstm = connection.prepareStatement(sql);
        if (args!=null&&args.length>0){
            for (int i=0;i<args.length;i++){
                pstm.setObject(i+1,args[i]);
            }
        }
        pstm.executeUpdate();
    }

    public List<T> getList(Connection connection,String sql,Class<T> clazz,Object...args) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        List<T> list = new ArrayList();
        PreparedStatement pstm = connection.prepareStatement(sql);
        if (args!=null&&args.length>0){
            for (int i=0;i<args.length;i++){
                pstm.setObject(i+1,args[i]);
            }
        }
        ResultSet rs = pstm.executeQuery();
        ResultSetMetaData rsmd= rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        while (rs.next()) {
            T t = clazz.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = rsmd.getColumnLabel(i);
                Object value = rs.getObject(columnLabel);
                Field field = clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(t, value);
            }
            list.add(t);
        }
        return list;
    }
    public T getOne(Connection conn,String sql,Class<T> clazz,Object... args) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
        T t = null;
        PreparedStatement pstmt = conn.prepareStatement(sql);
        if (args!= null && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                pstmt.setObject(i + 1, args[i]);
            }
        }
        //执行sql
        ResultSet rs = pstmt.executeQuery();
        //获取数据库表的元数据对象
        ResultSetMetaData rsmd = rs.getMetaData();
        //获取数据库的列的总数
        int columnCount = rsmd.getColumnCount();
        if(rs.next()) {
            t =  clazz.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = rsmd.getColumnLabel(i);
                Object columnValue = rs.getObject(columnLabel);

                Field field = clazz.getDeclaredField(columnLabel);

                //开启权限
                field.setAccessible(true);

                field.set(t, columnValue);
            }

            return t;
        }
        return null;
    }
}
